package com.aaa.vegetablemarketexpress.controller;

import com.aaa.vegetablemarketexpress.entity.Shop;
import com.aaa.vegetablemarketexpress.entity.ShopProduct;
import com.aaa.vegetablemarketexpress.entity.User;
import com.aaa.vegetablemarketexpress.service.ShopProductService;
import com.aaa.vegetablemarketexpress.service.ShopService;
import com.aaa.vegetablemarketexpress.util.Page;
import com.aaa.vegetablemarketexpress.util.Result;
import com.aaa.vegetablemarketexpress.util.ResultUtil;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @FileName: ShopProductController
 * @Description:
 * @Author: 张钰哲
 * @CreateTime: 2025/9/12 14:51
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("shopProduct")
@Log4j2
public class ShopProductController {
    @Resource
    private ShopProductService shopProductService;
    @Resource
    private ShopService shopService;

    /**
     * 根据ID查询关联
     * @param id
     * @return
     */
    @PostMapping("/selectById")
    public Result selectShopProductById(@RequestParam Long id) {
        log.info("查询店铺商品关联，ID: {}", id);
        return ResultUtil.success(shopProductService.selectShopProductById(id));
    }

    /**
     * 分页查询关联列表
     * @param page
     * @return
     */
    @PostMapping("/selectList")
    public Result selectShopProductList(@RequestBody Page<ShopProduct> page) {
        log.info("分页查询店铺商品关联列表");
        return ResultUtil.success(shopProductService.selectShopProductList(page));
    }

    /**
     * 根据店铺ID查询商品ID列表
     * @param shopId
     * @return
     */
    @PostMapping("/selectProductIdsByShopId")
    public Result selectProductIdsByShopId(@RequestParam Long shopId) {
        log.info("根据店铺ID查询商品ID列表，店铺ID: {}", shopId);
        return ResultUtil.success(shopProductService.selectProductIdsByShopId(shopId));
    }

    /**
     * 根据商品ID查询店铺ID列表
     * @param productId
     * @return
     */
    @PostMapping("/selectShopIdsByProductId")
    public Result selectShopIdsByProductId(@RequestParam Long productId) {
        log.info("根据商品ID查询店铺ID列表，商品ID: {}", productId);
        return ResultUtil.success(shopProductService.selectShopIdsByProductId(productId));
    }

    /**
     * 新增关联
     * @param shopProduct
     * @return
     */
    @PostMapping("/insert")
    public Result insertShopProduct(@RequestBody ShopProduct shopProduct) {
        log.info("新增店铺商品关联，店铺ID: {}, 商品ID: {}",
                shopProduct.getShopId(), shopProduct.getProductId());
        try {
            int result = shopProductService.insertShopProduct(shopProduct);
            if (result > 0) {
                return ResultUtil.success("新增关联成功");
            } else {
                return ResultUtil.failed("新增关联失败");
            }
        } catch (Exception e) {
            log.error("新增店铺商品关联失败", e);
            return ResultUtil.failed("新增关联失败: " + e.getMessage());
        }
    }

    /**
     * 批量新增关联
     * @param shopProductList
     * @return
     */
    @PostMapping("/batchInsert")
    public Result batchInsertShopProduct(@RequestBody List<ShopProduct> shopProductList) {
        log.info("批量新增店铺商品关联，数量: {}", shopProductList.size());
        try {
            int result = shopProductService.batchInsertShopProduct(shopProductList);
            return ResultUtil.success("成功新增 " + result + " 条关联");
        } catch (Exception e) {
            log.error("批量新增店铺商品关联失败", e);
            return ResultUtil.failed("批量新增关联失败: " + e.getMessage());
        }
    }

    /**
     * 删除关联
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public Result deleteShopProduct(@RequestParam Long id) {
        log.info("删除店铺商品关联，ID: {}", id);
        try {
            int result = shopProductService.deleteShopProductById(id);
            if (result > 0) {
                return ResultUtil.success("删除关联成功");
            } else {
                return ResultUtil.failed("删除关联失败");
            }
        } catch (Exception e) {
            log.error("删除店铺商品关联失败", e);
            return ResultUtil.failed("删除关联失败: " + e.getMessage());
        }
    }

    /**
     * 根据店铺ID和商品ID删除关联
     * @param shopId
     * @param productId
     * @return
     */
    @DeleteMapping("/deleteByShopAndProduct")
    public Result deleteShopProduct(@RequestParam Long shopId, @RequestParam Long productId) {
        log.info("删除店铺商品关联，店铺ID: {}, 商品ID: {}", shopId, productId);
        try {
            int result = shopProductService.deleteShopProduct(shopId, productId);
            if (result > 0) {
                return ResultUtil.success("删除关联成功");
            } else {
                return ResultUtil.failed("删除关联失败");
            }
        } catch (Exception e) {
            log.error("删除店铺商品关联失败", e);
            return ResultUtil.failed("删除关联失败: " + e.getMessage());
        }
    }

    /**
     * 更新店铺的商品关联
     * @param shopId
     * @param productIds
     * @return
     */
    @PostMapping("/updateShopProducts")
    public Result updateShopProducts(@RequestParam Long shopId, @RequestBody List<Long> productIds) {
        log.info("更新店铺的商品关联，店铺ID: {}, 商品数量: {}", shopId, productIds.size());
        try {
            int result = shopProductService.updateShopProducts(shopId, productIds);
            return ResultUtil.success("成功更新 " + result + " 条关联");
        } catch (Exception e) {
            log.error("更新店铺商品关联失败", e);
            return ResultUtil.failed("更新关联失败: " + e.getMessage());
        }
    }
    /**
     * 商家为自己的店铺添加商品
     * 包含权限验证，确保商家只能为自己的店铺添加商品
     */
    // ShopProductController.java
    @PostMapping("/addProductToMyShop")
    public Result addProductToMyShop(@RequestParam(required = false) Long shopId,
                                     @RequestParam(required = false) Long productId,
                                     HttpSession session) {
        try {
            log.info("将商品关联到店铺: shopId={}, productId={}", shopId, productId);

            // 验证参数
            if (shopId == null || productId == null) {
                log.error("参数不能为空: shopId={}, productId={}", shopId, productId);
                return ResultUtil.failed("参数不能为空");
            }

            // 验证店铺是否存在且属于当前用户
            Shop shop = shopService.selectShopById(shopId);
            if (shop == null) {
                log.error("店铺不存在: shopId={}", shopId);
                return ResultUtil.failed("店铺不存在");
            }

            // 获取当前登录用户
            User currentUser = (User) session.getAttribute("userInfo");
            if (currentUser == null) {
                log.error("用户未登录");
                return ResultUtil.failed("用户未登录");
            }

            // 检查关联是否已存在
            ShopProduct existing = shopProductService.selectShopProduct(shopId, productId);
            if (existing != null) {
                log.info("商品已关联到店铺: shopId={}, productId={}", shopId, productId);
                return ResultUtil.success("商品已关联到店铺");
            }

            // 创建关联记录
            ShopProduct shopProduct = new ShopProduct();
            shopProduct.setShopId(shopId);
            shopProduct.setProductId(productId);
            shopProduct.setCreateBy(currentUser.getUserName());
            shopProduct.setUpdateBy(currentUser.getUserName());
            shopProduct.setCreateTime(new Date());
            shopProduct.setUpdateTime(new Date());

            int result = shopProductService.insertShopProduct(shopProduct);
            if (result > 0) {
                log.info("商品关联成功: shopId={}, productId={}", shopId, productId);
                return ResultUtil.success("商品关联成功");
            } else {
                log.error("商品关联失败: shopId={}, productId={}", shopId, productId);
                return ResultUtil.failed("商品关联失败");
            }
        } catch (Exception e) {
            log.error("商品关联店铺失败", e);
            return ResultUtil.failed("商品关联失败: " + e.getMessage());
        }
    }

    /**
     * 根据商品id查询店铺名称
     * @param productId
     * @return
     */
    @PostMapping("/getShopNameByProductId")
    public Result getShopNameByProductId(@RequestParam Long productId) {
        String shopName = shopProductService.getShopNameByProductId(productId);
        return ResultUtil.success(shopName);
    }

}
